<script setup lang="ts" name="Preview">
import { preview } from "./generate"
import { onBeforeRouteLeave } from "vue-router";
import { RouterRecord } from "@/global/record/RouterRecord";
import { GENERATE_JSON, VIEW_TYPE_ENUM } from "@/views/tool/generate/const";

const { proxy } = getCurrentInstance();

const router = useRouter();

const route = useRoute();

const viewData = ref<ViewPageRecord>({})

const viewType = ref(VIEW_TYPE_ENUM.index);

/** 获取数据 */
function getData() {

  let generateJson = localStorage.getItem(GENERATE_JSON);
  if (generateJson) {
    let generate = JSON.parse(generateJson);
    viewData.value = preview(generate);
  }
}

/** 复制代码 */
function handleCopy() {
  let text = viewData.value[viewType.value];
  const elm = document.createElement('textarea');
  elm.value = text;
  document.body.appendChild(elm);
  elm.select();
  let successful = document.execCommand('copy');
  document.body.removeChild(elm);

  if (successful) {
    proxy["$modal"].msgSuccess("复制成功！");
  } else {
    proxy["$modal"].msgError("该浏览器不支持点击复制到剪贴板!");
  }
}

/** 返回 */
function handleExit() {
  router.go(-1);
}

onBeforeRouteLeave(() => {
  useTagsViewStore().delView(<RouterRecord>route);
})


getData();
</script>

<template>
  <div class="app-container prev-box">
    <div class="back-item prev-item">
      <div class="table-top mb8">
        <div class="title title-left">
        </div>
        <el-button
            class="top-right-btn"
            icon="DocumentCopy"
            type="primary"
            plain
            @click="handleCopy"
        >复制
        </el-button>
        <el-button
            class="top-right-btn"
            icon="Back"
            type="warning"
            plain
            @click="handleExit"
        >返回
        </el-button>
      </div>
      <el-tabs v-model="viewType">
        <el-tab-pane
            v-for="(item) in VIEW_TYPE_ENUM"
            :label="item"
            :name="item"
            :key="item"
        >
        </el-tab-pane>
      </el-tabs>
      <pre class="code-box">{{ viewData[viewType] }}</pre>
      <div class="line-magin" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.top-right-btn {
  z-index: 99;
}

:deep(.el-tabs) {
  margin-top: -40px !important;
}

.prev-box {
  height: 100%;
  overflow: hidden;

  .prev-item {
    height: 100%;
  }
}

.code-box {
  margin-top: 0;
  height: calc(100% - 70px);
  overflow-y: auto;
}
</style>
